package ocean.chinacraft.common;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.goal.GoalSelector;
import net.minecraft.world.entity.ai.goal.LookAtPlayerGoal;
import net.minecraft.world.entity.ai.goal.WrappedGoal;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import ocean.chinacraft.common.constants.Constants;
import ocean.chinacraft.common.world.entity.ai.goal.ModAttackGoal;
import ocean.chinacraft.common.world.entity.ai.goal.ModLookAtGoal;
import ocean.chinacraft.common.world.item.armor.SilkNightArmor;

import java.util.Iterator;

/**
 * 事件
 *
 * @author zhang
 * @since 2022/11/4 19:24
 **/
public class ModEvents {

    @Mod.EventBusSubscriber(modid = Constants.MOD_ID, value = Dist.CLIENT)
    public static class ForgeClientEvents {
        @SubscribeEvent
        public static void onPreRenderPlayer(final RenderPlayerEvent.Pre event) {
            if (SilkNightArmor.invalid(event.getEntity())) {
                event.setCanceled(true);
            }
        }
    }

    @Mod.EventBusSubscriber(modid = Constants.MOD_ID)
    public static class ForgeEvents {
        @SubscribeEvent
        public static void onEntityJoinWorldEvent(final EntityJoinLevelEvent event) {
            Entity entity = event.getEntity();
            if (entity.isAlive() && entity instanceof Monster monster) {
                GoalSelector targetSelector = monster.targetSelector;
                GoalSelector goalSelector = monster.goalSelector;
                Iterator<WrappedGoal> iterator = goalSelector.getAvailableGoals().iterator();
                while (iterator.hasNext()) {
                    Goal nextGoal = iterator.next().getGoal();
                    if (nextGoal instanceof LookAtPlayerGoal) {
                        goalSelector.getAvailableGoals().stream().filter((res) -> res.getGoal() == nextGoal).filter(WrappedGoal::isRunning).forEach(WrappedGoal::stop);
                        iterator.remove();
                    }
                }
                targetSelector.addGoal(2, new ModAttackGoal(monster, false));
                goalSelector.addGoal(1, new ModLookAtGoal(monster, Player.class, 8F));
            }
        }
    }
}
